<template>
    <div class="databaseConfig app-container">
      <div class="menu el-col-14">
        <el-button type="default" @click="dialogAddVisible=true">添加</el-button>
      </div>
      <div class="search el-col-10">
        <el-input placeholder="搜索关键字" v-model="params.search" @keyup.enter.native="search" class="input-with-select">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>

      <el-table :data="dataList" v-loading="isLoading"  element-loading-text="拼命加载中" border style="width: 100%">
        <el-table-column sortable align="center" min-width="" prop="name" label="库名"></el-table-column>
        <el-table-column sortable align="center" min-width="" prop="user" label="用户名"></el-table-column>
        <el-table-column sortable align="center" min-width="" prop="host" label="地址"></el-table-column>
        <el-table-column sortable align="center" min-width="" prop="port" label="端口"></el-table-column>
        <!-- 环境标签，利用固定值envs列表循环 -->
        <el-table-column align="center" width="120" prop="env" label="所属环境"
                         :filters="envs" :filter-method="filterTag" filter-placement="bottom-end">
          <template slot-scope="scope" >
            <span v-for="env in envs">
              <span v-show="scope.row.env===env.value">
                <el-tag :type="env.color"
                  disable-transitions>{{ env.text }}</el-tag>
                </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column sortable align="center" width="" prop="remark" label="备注"></el-table-column>
        <el-table-column sortable align="center" width="160" prop="utime" label="更新时间"></el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="110">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="edit(scope.row)">编辑</el-button>
            <el-button size="small" type="text" @click="deleteClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pageination" v-show="total>5">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="[5, 10, 15, 20]"
          :current-page.sync="params.page"
          :page-size="params.page_size"
          :total="total">
        </el-pagination>
      </div>

      <!-- 新增项目对话框 -->
      <el-dialog title="新增用户组" :visible.sync="dialogAddVisible" width="40%">
        <el-form :model="databaseItem" status-icon :rules="rules" ref="databaseAddForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="地址" prop="host">
            <el-input type="text" v-model="databaseItem.host" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="端口" prop="port">
            <el-input type="text" v-model="databaseItem.port" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="库名" prop="name">
            <el-input type="text" v-model="databaseItem.name" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="环境" prop="env">
            <el-select class="select" v-model="databaseItem.env" placeholder="请选择环境">
              <el-option v-for="env in envs"
                         :label="env.text" :value="env.value" :key="env.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户名" prop="user">
            <el-input type="text" v-model="databaseItem.user" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="databaseItem.password" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="text" v-model="databaseItem.remark" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item class="btn-wrapper">
            <el-button size="small" @click="handleCloseAdd">关闭</el-button>
            <el-button size="small" :loading="isLoading" type="primary" @click="submitAdd">添加</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 编辑项目对话框 -->
      <el-dialog title="新增用户组" :visible.sync="dialogEditVisible" width="40%">
        <el-form :model="databaseItem" status-icon :rules="rules" ref="databaseEditForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="地址" prop="host">
            <el-input type="text" v-model="databaseItem.host" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="端口" prop="port">
            <el-input type="text" v-model="databaseItem.port" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="库名" prop="name">
            <el-input type="text" v-model="databaseItem.name" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="环境" prop="env">
            <el-select class="select" v-model="databaseItem.env" placeholder="请选择环境">
              <el-option v-for="env in envs"
                         :label="env.text" :value="env.value" :key="env.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户名" prop="user">
            <el-input type="text" v-model="databaseItem.user" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="databaseItem.password" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="text" v-model="databaseItem.remark" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item class="btn-wrapper">
            <el-button size="small" @click="handleCloseEdit">关闭</el-button>
            <el-button size="small" :loading="isLoading" type="primary" @click="editSubmit">添加</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { getDatabasesList, deleteDatabase, createDatabase, updateDatabase } from '@/api/sqlaudit'

  export default {
    name: 'databaseConfig',
    computed: {
      ...mapGetters({ // vuex存储的列表，若需要加可以在store user.js加
        envs: 'envs'
      })
    },
    data() {
      const checkNumber = (rule, value, callback) => { // 数字校验
        if (/^\d+$/.test(value)) {
          callback()
        } else {
          callback(new Error('端口不能为空，且必须是数字'))
        }
      }
      return {
        isLoading: false,
        dialogAddVisible: false,
        dialogEditVisible: false,
        total: 0,
        params: {
          page: 1,
          page_size: 10,
          search: ''
        },
        dataList: [],
        databaseItem: {
          env: 'dev'
        },
        rules: {
          name: [{ required: true, message: '数据库名不能为空', trigger: 'blur' }],
          host: [{ required: true, message: '数据库地址不能为空', trigger: 'blur' }],
          port: [{ required: true, trigger: 'blur', validator: checkNumber }],
          user: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
          password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
          env: [{ required: true, message: '环境不能为空', trigger: 'blur' }]
        }
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      fetchData() {
        this.isLoading = true
        getDatabasesList(this.params).then(
          res => {
            this.isLoading = false
            this.dataList = res.results
            this.total = res.count
          })
      },
      // 改变页码和页面大小时获取对应的数据
      handleCurrentChange(val) {
        this.params.page = val
        this.fetchData()
      },
      handleSizeChange(val) {
        this.params.page_size = val
        this.fetchData()
      },
      filterTag(value, row) {
        return row.env === value
      },
      submitAdd() {
        this.$refs['databaseAddForm'].validate(
          (valid) => {
            if (!valid) {
              return
            }
            this.isLoading = true
            createDatabase(this.databaseItem).then(
              () => {
                this.handleCloseAdd()
                this.fetchData()
                this.$message.success('添加数据连接配置成功')
              }).catch(
              () => {
                this.isLoading = false
                this.handleCloseAdd()
                this.$message.error('添加数据连接配置失败')
              })
          })
      },
      handleCloseAdd() {
        this.isLoading = false
        this.dialogAddVisible = false
        this.$refs['databaseAddForm'].resetFields()
        this.databaseItem = { env: 'dev' }
      },
      handleCloseEdit() {
        this.isLoading = false
        this.dialogEditVisible = false
        this.$refs['databaseEditForm'].resetFields()
        this.databaseItem = { env: 'dev' }
      },
      search() {
        this.fetchData()
      },
      deleteClick(db) {
        this.$confirm(`确认删除数据库 ${db.name} 的连接信息吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(
          () => {
          // console.log(value.member)
            deleteDatabase(db.id).then(
              () => {
                // this.isLoading = false
                this.fetchData()
                this.$message.success('删除数据库配置成功')
              }).catch(
              () => {
                this.$message.error('删除数据库配置失败')
              })
          }).catch(
          () => {
            this.$message.info('已取消删除')
          })
      },
      edit(row) {
        this.databaseItem = row
        this.dialogEditVisible = true
      },
      editSubmit() {
        this.$refs['databaseEditForm'].validate(
          (valid) => {
            if (!valid) {
              return
            }
            this.isLoading = true
            const { id, ...data } = this.databaseItem
            updateDatabase(id, data).then(
              () => {
                this.handleCloseEdit()
                this.$message.success('修改数据库连接成功')
                this.fetchData()
              }).catch(
              () => {
                this.$message.error('修改数据库连接失败')
              })
          })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .databaseConfig {
    .pageination {
      text-align: center;
      margin-top: 15px;
    }
    .search {
      margin-bottom: 10px;
    }
    .btn-wrapper {
      text-align: right;
    }
    .select {
      width: 100%;
    }
  }
</style>
